package com.acdc.mqtt.service.impl;

import com.acdc.mqtt.service.MessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
import com.acdc.mqtt.entity.MqttMsg;
import com.acdc.mqtt.entity.WkPub;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.acdc.service.IIotModuleService;
import com.acdc.domain.IotModule;
import com.acdc.service.DLT698InstructionSender;
import com.acdc.service.IIotModuleLogService;
import com.acdc.domain.IotModuleLog;
import java.time.LocalDateTime;
import com.acdc.device.service.IMeterDeviceService;
import com.acdc.device.domain.MeterDevice;
import java.util.List;
@Slf4j
@Component
public class WkPubHandler implements MessageHandler {

    @Autowired
    private IIotModuleService iotModuleService;

    @Autowired
    private IIotModuleLogService iotModuleLogService;

    @Autowired
    private DLT698InstructionSender dlt698Sender;

    @Autowired
    private IMeterDeviceService meterDeviceService;

    @Override
    public void handleMessage(String topic, String message) {
        String imei = topic.split("\\/")[2];
        log.info("IMIEI: {}, WkPubHandler: {}", imei, message);

        try {
            MqttMsg<WkPub> mqttMsg = new ObjectMapper().readValue(message, new TypeReference<MqttMsg<WkPub>>() {});
            WkPub wkPub = mqttMsg.getData();
            log.info("WkPub: {}", wkPub);
            IotModule iotModule = iotModuleService.selectIotModuleByImei(imei);
            
            if (iotModule == null) {
                // 添加新的物联网模块
                iotModule = new IotModule();
                iotModule.setImei(imei);
                iotModule.setFvn(wkPub.getFvn());
                iotModule.setHv(wkPub.getHv());
                iotModuleService.insertIotModule(iotModule);
                log.info("添加新的物联网模块: {}", iotModule);
                // 发送请求ServerAddress指令
                dlt698Sender.queryServerAddress(imei);
            } else {
                // 更新物联网模块
                iotModule.setFvn(wkPub.getFvn());
                iotModule.setHv(wkPub.getHv());
                iotModuleService.updateIotModule(iotModule);
                log.info("更新物联网模块: {}", iotModule);
                // 更新开关状态
                if ("kj".equals(wkPub.getField())) {
                    MeterDevice query = new MeterDevice();
                    query.setIotModuleId(iotModule.getId());
                    List<MeterDevice> meterDeviceList = meterDeviceService.selectMeterDeviceList(query);
                    for (MeterDevice meterDevice : meterDeviceList) {
                        if (wkPub.getPwr_sta().equals("1")) {
                            meterDevice.setDeviceStatus("3");
                        } else {
                            meterDevice.setDeviceStatus("2");
                        }
                        meterDeviceService.updateMeterDevice(meterDevice);
                    }
                }
            }
            // 保存操作日志
            saveIotModuleLog(imei, "wk_up", mqttMsg);
        } catch (JsonProcessingException e) {
            log.error("WkPubHandler: {}", e.getMessage());
        }
    }

    private void saveIotModuleLog(String imei, String opType, MqttMsg<?> mqttMsg) {
        try {
            IotModule iotModule = iotModuleService.selectIotModuleByImei(imei);
            IotModuleLog iotModuleLog = new IotModuleLog();
            iotModuleLog.setIotModuleId(iotModule.getId());
            iotModuleLog.setOpType(opType);
            iotModuleLog.setOpData(mqttMsg.toString());
            iotModuleLog.setOpTime(LocalDateTime.now());
            iotModuleLogService.insertIotModuleLog(iotModuleLog);
        } catch (Exception e) {
            log.error("保存IoT模块日志失败: {}", e.getMessage());
        }
    }
}
